﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentValidation;
using FluentValidation.Results;
using Microhard.Permission.Interface;
using Microhard.Core;

namespace Microhard.Permission.Validator
{
    public class UserValidator : AbstractValidator<Microhard.Permission.Models.User>
    {
        public UserValidator()
        {
            IUser userFuc = IoC.Resolve<IUser>();
            RuleSet("Insert", () =>
            {
                RuleFor(u => u.UserName).NotEmpty().WithMessage(MsgForPermission.NeedUserName);
                RuleFor(u => u.UserName).Length(1, 10).WithMessage(MsgForPermission.MaxLenOfUserName);
                RuleFor(u => u.password).NotEmpty().WithMessage(MsgForPermission.NeedPWD);
                RuleFor(u => u.password).Length(6, 20).WithMessage(MsgForPermission.PWDLength);
                RuleFor(u => u.UserRealName).NotEmpty().WithMessage(MsgForPermission.NeedUserRealName);
                Custom(u =>
                {
                    Microhard.Core.DBUtility.ValidationResult result = userFuc.UserNameValidating(u);
                    if (!result.IsValid)
                    {
                        var error = result.ErrorMsg.First();
                        return new ValidationFailure(error.Key, error.Value);
                    }
                    return null;
                });
                Custom(u =>
                {
                    if (u.Roles == null || u.Roles.Count == 0 || u.Roles[0].RoleId == Guid.Empty)
                    {
                        return new ValidationFailure("NeedRole", MsgForPermission.NeedRole);
                    }
                    return null;
                });
            });


            RuleSet("Update", () =>
            {
                RuleFor(u => u.UserRealName).NotEmpty().WithMessage(MsgForPermission.NeedUserRealName);
                Custom(u =>
                {
                    if (u.Roles == null || u.Roles.Count == 0 || u.Roles[0].RoleId == Guid.Empty)
                    {
                        return new ValidationFailure("NeedRole", MsgForPermission.NeedRole);
                    }
                    return null;
                });
            });


        }
    }
}
